﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp4
{
    class DBHelper
    {
        //创建链接语句
        public static string sql = "server=.;database=Student;Integrated Security=true;";
        //创建链接对象
        public static SqlConnection conn = null;
        //链接保护
        public static void InitConnection() 
        {
            if (conn==null) 
            {
                conn = new SqlConnection(sql);
            }
            if (conn.State == ConnectionState.Closed) 
            {
                conn.Open();
            }
            if (conn.State == ConnectionState.Broken) 
            {
                conn.Close();
                conn.Open();
            }
        }
        //增删改
        //返回值 bool
        //参数 sql
        public static bool GetNonQuery(string sql) 
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            int i = cmd.ExecuteNonQuery();
            conn.Close();
            return i > 0;
        }
        //查询
        //返回值 SqlDataReader
        //参数 sql
        public static SqlDataReader Select(string sql) 
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, conn);
            return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
        }
        //聚合函数
        //返回值
        //参数 sql
        public static object ExecuteScalar(string sql) 
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql);
            object result = cmd.ExecuteScalar();
            conn.Close();
            return result;
        }
    }
}
